import os
from typing import Dict, Any

import pandas as pd
import yaml

from config import ROOT_DIR
from utils.data.loader import BinanceLoader
from utils.error import PreparationError
from utils.strategy.conf.base import BaseConf, kline_map


class ActualConf(BaseConf):

    def __init__(self, strategy_name: str,
                 account: str, s_time: str = '1900-1-1', e_time: str = '2100-1-1', **kwargs):
        super().__init__(strategy_name, s_time, e_time, **kwargs)
        try:
            with open(os.path.join(ROOT_DIR, 'account.yaml'), 'r', encoding='utf-8') as f:
                data: Dict[str, Any] = yaml.safe_load(f)
            self.api_key = data['accounts'][account]['apiKey']
            self.secret_key = data['accounts'][account]['secretKey']
        except Exception as e:
            raise PreparationError(f'读取账户配置失败{e.__str__()}')
        self.account_name: str = account

    def load_data(self, exe_time: int = None) -> pd.DataFrame:
        """
        获取数据
        :return:
        """
        if exe_time is None:
            exe_time = 0

        loader = BinanceLoader(self.period, symbols=self.strategy.symbols, batch_size=self.strategy.KlineBatchSize)
        s: int = exe_time - self.period * self.strategy.historyKlineCount * self.strategy.KlineBatchSize
        return loader.fetch(start=s, end=exe_time, type_=self.strategy.dataType,
                            funding_rate=self.strategy.withFundingRate)
